const { ccclass, property } = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

    @property
    lightColor: cc.Color = cc.Color.WHITE;
    @property({ type: cc.Float, min: 0, max: 180 })
    lightAngle: number = 80;
    @property({ type: cc.Float, min: 0, max: 1 })
    lightWidth: number = .2;

    @property
    swpeepTime: number = 1;
    @property
    totalTime: number = 5;

    @property
    reverse: boolean = false;

    _mat: cc.Material = null;

    _startPoint: cc.Vec2 = null;
    _endPoint: cc.Vec2 = null;
    _stepPoint: cc.Vec2 = null;
    _curPoint: cc.Vec2 = null;

    _curTime: number = 0;

    start() {
        let renderComp = this.node.getComponent(cc.Sprite) || this.node.getComponent(cc.Label);
        this._mat = renderComp.getMaterial(0);
        this.reset();
    }

    reset() {
        let dblLightWidth = 2 * this.lightWidth;
        this._startPoint = cc.v2(-dblLightWidth, -dblLightWidth);
        this._endPoint = cc.v2(1 + dblLightWidth, 1 + dblLightWidth);
        this._stepPoint = this._endPoint.sub(this._startPoint).div(this.swpeepTime);
        this._curPoint = this.reverse ? this._endPoint.clone() : this._startPoint.clone();
        this._curTime = 0;
        this._mat.setProperty('lightColor', this.lightColor);
        this._mat.setProperty('lightAngle', this.lightAngle);
        this._mat.setProperty('lightWidth', this.lightWidth);
        this._mat.setProperty('lightCenterPoint', this._curPoint);
    }

    update(dt: number) {
        this._curTime += dt;
        if (this._curTime <= this.swpeepTime) {
            this.reverse ? this._curPoint.subSelf(this._stepPoint.mul(dt)) : this._curPoint.addSelf(this._stepPoint.mul(dt));
            this._mat.setProperty('lightCenterPoint', this._curPoint);
        }
        if (this._curTime >= this.totalTime) {
            this._curTime = 0;
            this._curPoint = this.reverse ? this._endPoint.clone() : this._startPoint.clone();
        }
    }
}
